import random

from tenacity import retry, stop_after_attempt, wait_fixed

from com.util.tcp.tcpClient import TcpClient, tcp_borrow, tcp_recycle, clearPool

commonReq = {
    "userId": "111",
    "token": "111",
    "termType": 2,
    "deviceNo": "111"
}


class TcpService(object):
    """
    对外提供服务
    """

    # 借用对象
    def __setObj__(self):
        self.pooled_object = tcp_borrow()
        self.con: TcpClient = self.pooled_object.use()

    # 归还
    def tcp_recycle(self):
        tcp_recycle(self.pooled_object)

    # 重试一次
    @retry(stop=stop_after_attempt(1), wait=wait_fixed(3))
    def getStockBaseInfos(self, stock, marketType):
        self.__setObj__()
        data = {"commonReq": commonReq,
                "stockKeys": [{"marketType": int(marketType),
                               "stockId": str(stock)}]}
        # 发送数据
        sequeueNo = random.randint(1, 9999)
        self.con.sendTcpData("2002", sequeueNo, data)
        self.con.sendTcpData("2003", sequeueNo, data)

        # 接受数据
        res_2002 = self.con.receiveData("2002", sequeueNo)
        res_2003 = self.con.receiveData("2003", sequeueNo)

        returnRes = {}
        # 拼装数据
        if res_2003.__len__() > 0:
            snapshots = res_2003['snapshots']
            returnRes: dict = snapshots[0]
        if res_2002.__len__() > 0:
            stockBaseInfos = res_2002['stockBaseInfos']
            returnRes.setdefault('stockBaseInfos', stockBaseInfos)

        # 数据为空时需重试1次
        if returnRes.__len__() == 0:
            self.con.state = False
            self.tcp_recycle()
            raise RuntimeError
        else:
            self.tcp_recycle()
            return returnRes

    @retry(stop=stop_after_attempt(1), wait=wait_fixed(3))
    def getMarketOverview(self, marketType):
        self.__setObj__()
        data = {"commonReq": commonReq,
                "marketType": marketType,
                "version": 4200}

        # 发送数据
        sequeueNo = random.randint(1, 9999)
        self.con.sendTcpData("2001", sequeueNo, data)
        # 接受数据
        res = self.con.receiveData("2001", sequeueNo)

        # 数据为空时需重试
        if res.__len__() == 0:
            self.con.state = False
            self.tcp_recycle()
            raise RuntimeError

        stockids = res['marketBaseInfo']['typeProperty']
        resultCode = []
        for obj in stockids:
            stockid = obj['stockId']
            marketType = obj['marketType']
            resultCode.append(f"{stockid}.{marketType}")

        self.tcp_recycle()
        return resultCode

    def close(self):
        clearPool()
